package com.hits.buildqrcode.utils;

import com.hits.buildqrcode.service.CaseService;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Decoder;
import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.DocPicture;

import javax.imageio.stream.FileImageInputStream;
import javax.imageio.stream.FileImageOutputStream;

import java.io.*;
import java.util.UUID;

public class ImageUtils {

    private static Logger logger  = LoggerFactory.getLogger(ImageUtils.class);

    public static boolean base64StrToImage(String imgStr, String path) {
        if (imgStr == null)
            return false;
        BASE64Decoder decoder = new BASE64Decoder();
        FileImageOutputStream imageOutput = null;
        try {
            // 解密
            byte[] b = decoder.decodeBuffer(imgStr);
            //文件夹不存在则自动创建
            File tempFile = new File(path);
            if (!tempFile.getParentFile().exists()) {
                tempFile.getParentFile().mkdirs();
            }
            imageOutput = new FileImageOutputStream(new File(path));
            imageOutput.write(b, 0, b.length);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }finally {
            if (imageOutput!=null){
                try {
                    imageOutput.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    //图片到byte数组
    public static byte[] image2byte(String path) {
        byte[] data = null;
        FileImageInputStream input = null;
        ByteArrayOutputStream output = null;
        try {
            input = new FileImageInputStream(new File(path));
            output = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            int numBytesRead = 0;
            while ((numBytesRead = input.read(buf)) != -1) {
                output.write(buf, 0, numBytesRead);
            }
            data = output.toByteArray();
        } catch (FileNotFoundException ex1) {
            ex1.printStackTrace();
        } catch (IOException ex1) {
            ex1.printStackTrace();
        }finally {
            try {
                if (input!=null){
                    input.close();
                }
                if (output!=null){
                    output.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return data;
    }

    /**
     * 插入图片至页脚
     *
     * @param wordPath            word全路径(含文件及格式)
     * @param imagePath           图片全路径(含文件及格式)
     * @param savePath            生成文件存储全路径(含文件及格式)
     * @param horizontalAlignment 图片插入位置
     * @param imageHeight         图片高度
     * @param imageWidth          图片宽度
     * @param primaryCleaan       是否清除所有页脚
     */
    public static void insertPictureForFooter(String ajid,String wordPath, String imagePath, String savePath, HorizontalAlignment horizontalAlignment,
         float imageHeight, float imageWidth, boolean primaryCleaan) {
        //savePath="D:\\document\\qrCode\\"+ UUID.randomUUID().toString().replaceAll("-","")+".docx";
        if (StringUtils.isNotEmpty(wordPath) && StringUtils.isNotEmpty(imagePath)) {
            Document document=null;
            try {
                if(!new File(wordPath).exists()){
                    logger.error("二维码插入文书时发生异常，案件id为:"+ajid+"--文书路径:"+wordPath+"--二维码路径:"+imagePath);
                    return;
                }
                //加载word文档
                 document = new Document(wordPath);
                //获取第一个section
                Section section = document.getSections().get(0);
                if (primaryCleaan) {//删除页脚
                    section.getHeadersFooters().getFooter().getChildObjects().clear();
                }
                //加载页脚
                HeaderFooter footer = section.getHeadersFooters().getFooter();
                //添加段落到页脚
                Paragraph footerParagraph = footer.addParagraph();
                //插入图片并设置位置
                footerParagraph.getFormat().setHorizontalAlignment(horizontalAlignment);
                DocPicture footerPicture = footerParagraph.appendPicture(imagePath);
                footerPicture.setHeight(imageHeight);
                footerPicture.setWidth(imageWidth);
                //输出文件,不传则覆盖原有文件
                if (StringUtils.isNotEmpty(savePath)) {
                    wordPath = savePath;
                }
                document.saveToFile(wordPath, FileFormat.Docx);
                //屏蔽Evaluation Warning
                deleteHeaderDocForEvaluation(wordPath, "");
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                if (document!=null){
                    document.close();
                }
            }
        }
    }

    /**
     * 功能描述: 通过定位插入图片至页眉
     * @author w.k
     * @param wordPath word全路径(含文件及格式)
     * @param imagePath 图片全路径(含文件及格式)
     * @param savePath 生成文件存储全路径(含文件及格式)
     * @param imageHeight 图片高度
     * @param imageWidth 图片宽度
     * @return void
     */
    public static void insertPictureInHeaderByLocation (
            String ajid,String wordPath, String imagePath, String savePath, float imageHeight, float imageWidth) {
        if(StringUtils.isNotEmpty(wordPath) && StringUtils.isNotEmpty(imagePath)){
            try {
                if(!new File(wordPath).exists()){
                    logger.error("二维码插入文书时发生异常，案件id为:"+ajid+"--文书路径:"+wordPath+"--二维码路径:"+imagePath);
                    return;
                }
                Document document = new Document();
                document.loadFromFile(wordPath);
                Section section = document.getSections().get(0);
                HeaderFooter headerFooter = section.getHeadersFooters().getHeader();
                headerFooter.getParagraphs().clear();
                Paragraph otherpara = headerFooter.addParagraph();
                DocPicture picture = otherpara.appendPicture(imagePath);
                picture.setHorizontalPosition(421f);
                picture.setVerticalPosition(-22f);
                picture.setWidth(imageWidth);
                picture.setHeight(imageHeight);
                picture.setTextWrappingStyle(TextWrappingStyle.In_Front_Of_Text);
                if(StringUtils.isNotEmpty(savePath)){
                    wordPath = savePath;
                }
                document.saveToFile(wordPath, FileFormat.Docx);
                document.dispose();
                document.close();
                deleteHeaderDocForEvaluation(wordPath,"");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 屏蔽Evaluation Warning: The document was created with Spire.Doc for JAVA
     *
     * @param wordPath     word
     * @param saveFilePath word存储位置，不传则覆盖原文件
     */
    private static void deleteHeaderDocForEvaluation(String wordPath, String saveFilePath) {
        if (!StringUtils.isEmpty(wordPath)) {
            XWPFDocument document = null;
            InputStream inputStream = null;
            OutputStream outputStream = null;
            try {
                inputStream = new FileInputStream(wordPath);
                document = new XWPFDocument(inputStream);
                document.removeBodyElement(0);
                if (!StringUtils.isEmpty(saveFilePath)) {
                    outputStream = new FileOutputStream(saveFilePath);
                } else {
                    outputStream = new FileOutputStream(wordPath);
                }
                document.write(outputStream);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (document != null) {
                        document.close();
                    }
                    if (inputStream != null) {
                        inputStream.close();
                    }
                    if (outputStream != null) {
                        outputStream.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
